import os
from contextlib import contextmanager


# write Pretty API with context manager
# such as flexible indent
class Indenter:
    def __init__(self):
        self.level = 0

    def __enter__(self):
        self.level += 1
        # 别忘了return self
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.level -= 1

    def print(self, text):
        print('    ' * self.level + text)


# method1: in my own objects
class ManageFile:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.file = open(self.name, 'w')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

# method 2: use the contextlib.contextmanager decorator
@contextmanager
def manage_file(name):
    try:
        fg = open(name, 'a')
        # define a generator-based factory function for a resource
        yield fg
    finally:
        fg.close()


if __name__ == '__main__':
    filename = input("输入文件路径:\n")
    folder = filename.split('/')[0]
    fname = filename.split('/')[-1]
    if not os.path.exists(folder):
        os.mkdir(folder)
    if not os.path.exists(filename):
        fd = open(filename, 'a', encoding='utf-8')
        fd.close()
    else:
        print("文件已存在..")
        print("0————own object\n1————contextmanager")
    flag = input("请输入您选择的方式: ")
    if flag == 0:
        # method 1
        with ManageFile(filename) as f:
            f.write('hello python tricks!!\n')
            f.write('see you later!!\n')
    else:
        # method 2
        with manage_file(filename) as f:
            f.write('hello python tricks!!\n')
            f.write('see you later!!\n')

    # test on indent API
    with Indenter() as indent:
        indent.print('nihao')
        with indent:
            indent.print('hello')
            with indent:
                indent.print('kounijiwa')
        indent.print('byebye')

